//asideFnList 当python里面的装饰器用
let asideList = []
let asideFnList = []

let sql_list = []

sql_list.push(`
                select
    a.c_zyh as 住院号,
    b.管床医生 ,
    a.c_name as 姓名,
    c.c_sex_desc as 性别,
    c.c_age_str as 年龄,
    case when a.c_bed like '%床' then a.c_bed else concat(substring(a.c_bed,2,2),'床') end as 床号,
    c.c_ry_zd as 诊断,
    a.kyye as '住院费用',
    case datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d'))
    when 0 then '新入'
    when 1 then '昨入'
    else  datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d')) end as 天数  
    from patient_zyhs a
    left join  assistant_doctor b
    on a.c_zyh = b.住院号
    left join patient_details c
    on a.c_zyh = c.c_zyh
    where a.c_out_date is null
    order by 床号; 
    `)

sql_list.push(`
    select 
    a.c_code '1',
    a.c_name '2',
    c.性别 '3',
    a.c_age_desc '4',
    ifnull(e.c_addr_d,e.c_address) '5',
    c.门诊诊断 '6',
    concat('20',mid(a.c_code,1,2),'-',mid(a.c_code,3,2),'-',mid(a.c_code,5,2)) '7',
    d.d_name '8'
    from mz_p_code a
    left join mz_p_cost2 b on a.c_code=b.c_code 
    left join mz_p_jzxx c on a.c_code=c.就诊号
    left join doctor_id d on a.c_doctor_id=d.doctor_id
    left join mz_p_jbxx e on a.c_code=e.c_code 
    order by a.c_code desc limit 100
    `)

sql_list.push(`
    select
    a.c_zyh as 住院号,
    b.管床医生 ,
    a.c_name as 姓名,
    c.c_sex_desc as 性别,
    c.c_age_str as 年龄,
    case when a.c_bed like '%床' then a.c_bed else concat(substring(a.c_bed,2,2),'床') end as 床号,
    c.c_ry_zd as 诊断,
    a.kyye as '住院费用',
    case datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d'))
    when 0 then '新入'
    when 1 then '昨入'
    else  datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d')) end as 天数  
    from patient_zyhs a
    left join  assistant_doctor b
    on a.c_zyh = b.住院号
    left join patient_details c
    on a.c_zyh = c.c_zyh
    where a.c_out_date is null
    order by 床号;    
    `)

// 住院病程
sql_list.push(`
    select
    code,
    case when a.c_bed like '%床' then c_bed else concat(substring(c_bed,2,2),'床') end as 床号,
    a.c_zyh 住院号,
    a.c_name 姓名,
    e.c_sex_desc 性别,
    e.c_age_str 年龄,
    e.c_ry_zd 入院诊断,
    case when datediff(now(),f.c_ss_date)=0 then '今天' else datediff(now(),f.c_ss_date) end as  手术天数,
    case datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d'))
            when 0 then '新入'
            when 1 then '昨入'
            else  datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d')) end as 天数,
            case
    when g.c_ss_date is null then  '*'
    when datediff(now(),g.c_ss_date)=0 then  'ok' 
    when datediff(now(),g.c_ss_date)=1 then  '后'
    when datediff(now(),g.c_ss_date)=2 then  '明'
    when datediff(now(),g.c_ss_date)>2  then  '✓'   end as 治疗,
    case when e.c_dw_name is null then e.c_nowaddr_d else  e.c_dw_name end as 地址,
    case when e.c_tel is null then e.c_lx_tel else  e.c_tel end as 电话,
    a.c_wj_cost 费用
    from patient_zyhs a
    right join patient_self b on a.c_zyh = b.c_zyh
    left join assistant_doctor c on c.住院号 = b.c_zyh
    left join employee d on c.管床医生=d.name
    left join patient_details e on a.c_zyh = e.c_zyh
    left join operation f on a.c_zyh = f.c_zyh
    left join p_zl g on a.c_zyh = g.c_zyh
    where  a.c_out_date is null  and a.c_zyh is not null
    order by 床号
    `)


// 住院病程简
sql_list.push(`
    select
    a.c_zyh 住院号,
    case when a.c_bed like '%床' then c_bed else concat(substring(c_bed,2,2),'床') end as 床号,
    a.c_name 姓名,
    e.c_sex_desc 性别,
    e.c_age_str 年龄,
    e.c_ry_zd 入院诊断,
    case datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d'))
            when 0 then '新入'
            when 1 then '昨入'
            else  datediff(now(),date_format(a.c_ry_date,'%Y-%m-%d')) end as 天数,
    case when e.c_dw_name is null then e.c_nowaddr_d else  e.c_dw_name end as 地址
    from patient_zyhs a
    right join patient_self b on a.c_zyh = b.c_zyh
    left join assistant_doctor c on c.住院号 = b.c_zyh
    left join employee d on c.管床医生=d.name
    left join patient_details e on a.c_zyh = e.c_zyh
    left join operation f on a.c_zyh = f.c_zyh
    left join p_zl g on a.c_zyh = g.c_zyh
    where  a.c_out_date is null  and a.c_zyh is not null
    order by 床号
    `)

asideList.push('本科病人')
asideFnList.push(function (fnIndex) {
    $('.nav_title').empty().append(`<div class='back2'>${asideList[fnIndex]}</div>`)
    showDom(sql_list[3], '.content', table)
})



asideList.push('病程查询')
asideFnList.push(function (fnIndex) {
    $('.nav_title').empty().append(`<div class='back2'>${asideList[fnIndex]}</div>`)
    let rows = []
    rows.push(`<form><div>`)

    rows.push(`<div>住院号：<input type="text" name="c_zyh" style="margin:0"></div>`)
    rows.push(`<div>对应的病人打钩✓</div>`)
    rows.push(`<input type="submit" value="确定">`)
    rows.push(`<input type="reset" value="重置"></div>`)
    $.post('/sql/', { sql: sql_list[3] }, function (datas) {
        rows.push(checkbox_table(datas, 2))
        rows.push('</form>')
        let $con_cf = $('.content')
        $con_cf.empty().append(rows.join(''))
        let $input_checkbox = $('input[type="checkbox"]')
        $input_checkbox.on('change', function() {
            // 获取当前复选框的选中状态
            let isChecked = $(this).prop('checked')
            if (!isChecked){
                return
            }
            $input_checkbox.not($(this)).prop('checked',false)
            $('input[name="c_zyh"]').val($(this).val())

        })

        $('input[type="submit"]').on('click', function (event) {
            event.preventDefault()
            let title = $('input[name="c_zyh"]').val() ?? $('input[name="住院号"]:checked').val()
            let p_content = $('.content')

            $.post('/sql/', { sql: `select * from (${sql_list[4]}) as a where 住院号='${title}'` }, function (data) {
                p_content.empty().append(table2(data))
                $.post('/sql/',
                    {
                        sql: `
                        select concat('<p style="text-align: left;">时间：',p_date,' ',p_time,'<br></p>','<p style="text-align: left;">',p_bc,'<br><br></p>')  病程 
                        from p_bcjl where p_zyh ='${title}'                
                    `},
                    function (data) {
                        p_content.append(table(data))
                    }
                )
            })
        })
    })
})


asideList.push('保存病程')
asideFnList.push(function (fnIndex) {
    $('.nav_title').empty().append(`<div class='back2'>${asideList[fnIndex]}</div>`)
    let rows = []
    let data_sql = sql_list[3]
    rows.push(`<form><div>`)
    rows.push(`<div>日期：</div>`)
    rows.push(`<input type="date" name="operation-date" value="${getNowTime()}">`)
    rows.push(`<div>时间：</div>`)
    rows.push(`<input type="text" id="myTextbox" name="bc_time"  value="${formatTime()}" >`)
    rows.push(`<div>请输入病程记录：</div>
    `)

    rows.push(`<input type="submit" value="确定">`)
    rows.push(`<input type="submit" value="清空">`)
    rows.push(`<input type="reset" value="重置"></div>`)
    rows.push(`<textarea name="sql"></textarea>`)
    $.post('/sql/', { sql: data_sql }, function (datas) {
        rows.push('<div>')
        rows.push(checkbox_table(datas, 2))
        rows.push('</div>')
        rows.push('</form>')
        let $content = $('.content')
        $content.empty().append(rows.join(''))
        $('textarea').css("height", "120px")
        // let $input = $('.content input[type=checkbox]')
        $content.on('change','input[type="checkbox"]',function(){
            const $this = $(this);
            if (!$this.prop('checked')) return;  // 只处理选中状态
            
            // 获取当前作用域内所有多选框
            const $checkboxes = $('.content input[type="checkbox"]');
            
            // 单选逻辑：取消其他选中状态[2,4](@ref)
            $checkboxes.not(this).prop('checked', false);
            
            // 缓存文本域DOM引用（避免重复查询）
            const $textarea = $('textarea');
            
            // 安全处理SQL参数（防注入）
            const zyh = $this.val().replace(/'/g, "''");
            const safeSQL = `select p_bc from p_bcjl where p_zyh='${zyh}' and p_date='${$('input[type="date"]').val()}'`;
            
            // 发送请求
            $.post('/sql/', { sql: safeSQL }, function(data) {
                if (data[1][0]) {
                    let temp = data[1][0] + $textarea.val()
                    $textarea.val(
                        temp.replace(/<br>/g, '\n')
                      );
                }
            }).fail(() => console.error('请求失败'));
        });
       

        $('input[type="submit"]').eq(0).on('click', function (event) {
            event.preventDefault()
            let title = getFormData('form')
            let $p_zyh = $('input[name="住院号"]:checked').val()
            let $p_bcjl = $('textarea[name="sql"]').val().replace(/\n/g, '<br>')
            if ( $p_bcjl && $p_zyh ){
                $.post('/post', {
                sql: `
                REPLACE INTO p_bcjl (p_zyh, p_date, p_time, p_bc) 
                VALUES ('${$p_zyh}', '${title["operation-date"]}', '${title["bc_time"]}', '${$p_bcjl}');
                
                `})
                $('input[name="住院号"]:checked').prop('checked',false)
                $('textarea[name="sql"]').val('')
            } else {alert('不能为空，且要选住院号')}

        })

        $('input[type="submit"]').eq(1).on('click', function (event) {
            event.preventDefault()
            $('textarea[name="sql"]').val('')
        })
    })
})


asideList.push('病程查看')
asideFnList.push(function (fnIndex) {
    $('.nav_title').empty().append(`<div class='back2'>${asideList[fnIndex]}</div>`)
    let rows = []
    rows.push(`<form><div>`)
    rows.push(`<input type="date" name="operation-date" value="${getNowTime()}">`)
    rows.push(`<div>请选择日期</div>`)
    rows.push(`<input type="submit" value="确定"></div></form><div></div>`)
    $('.content').empty().append(rows.join(''))
    $('input[type="submit"]').on('click', function (event) {
        event.preventDefault()
        let title = getFormData('form')["operation-date"]
        $.post('/sql/', {
            sql: `
            select  concat_ws(' ','<p style="text-align: left;">',b.c_bed,b.c_name,c.c_age_str,c.c_ry_zd,c.c_nowaddr_d,'<br>','记录时间：',p_time,'<br>',a.p_bc,'</p><br>') 病程
            from p_bcjl a
            left join patient_zyhs b on a.p_zyh=b.c_zyh
            left join patient_details c on a.p_zyh = c.c_zyh
            where a.p_date='${title}'
            order by b.c_bed            
            ` }, function (data) {
            $('.content>div').empty().append(table(data))
        })
    })
    $('input[type="submit"]').click()

})



$(function () {
    circle_font($('.top'), "石林仁济医院")
    $('.nav_title').empty().append(`<div class='back2'>${asideList[0]}</div>`)
    showDom(sql_list[3], '.content', table)
    for (let i = 0; i < asideList.length; i++) {
        $('.aside').append(`<div data-index='${i}'>${asideList[i]}</div>`)
    }


    $('.aside').on('click', 'div', function () {
        let fnIndex = $(this).data('index')
        asideFnList[fnIndex](fnIndex)
        $(this).siblings().removeClass('back2')
        $(this).addClass('back2')
    })

})

